﻿namespace HynuIOTA.Web.Areas.Admin.Controllers
{
    using HynuIOTA.Entity;
    using HynuIOTA.Web.Filters;
    using HynuIOTA.Web.Helpers;
    using HynuIOTA.Web.Models;
    using System;
    using System.Data.Entity;
    using System.Linq;
    using System.Threading.Tasks;
    using System.Web;
    using System.Web.Mvc;
    using static HynuIOTA.Common.StringConst;

    public class ConfigController : BaseController
    {
        // GET: Admin/Config
        public async Task<ActionResult> Index()
        {
            var config = await OpContext.Service.WebConfig.Where(w => true).FirstOrDefaultAsync();
            if (config == null)
            {
                config = new WebConfig()
                {
                    Url = "www.hynu-iot.com",
                    Address = "湖南省衡阳市珠晖区衡州大道16号 计算机科学与技术学院 301办公室",
                    Author = "NewSky",
                    Copyright = "Copyright © 2018 衡阳师范学院物联网协会 All rights reserved.",
                    Description = "",
                    RecordCode = "湘备-93293848",
                    Statistics = "",
                    Telephone = "+86-8888888888",
                    Title = "衡阳师范学院物联网协会",
                    Version = "V 0.0.1 Beta",
                    UpdateTime = DateTime.Now
                };

                OpContext.Service.WebConfig.Add(config);
                try
                {
                    await OpContext.Service.SaveChangesAsync();
                    // 刷新缓存
                    OpContext.RefreshCacheDependency(CacheDependencyKeys.Config);
                }
                catch (Exception ex)
                {
                    return JsMsg(ex.Message);
                }
            }

            ViewBag.config = config;
            return View();
        }

        public async Task<ActionResult> PutConfig(PutWebConfigViewModel configViewModel)
        {
            if (ModelState.IsValid == false)
            {
                return JsonMsgFail(MODEL_VALIDATE_ERROR);
            }

            var config = await OpContext.Service.WebConfig.Where(c => true).FirstOrDefaultAsync();
            if (config == null)
            {
                return OpContext.JsonMsgFail(DATA_NOEXIST_ERROR);
            }

            Tools.SetValues(config, configViewModel, ModelState.Keys.ToArray());
            var result = await OpContext.SaveChangesAsync();

            if (result != null)
            {
                return result;
            }
            // 刷新缓存
            OpContext.RefreshCacheDependency(CacheDependencyKeys.Config);
            return OpContext.JsonMsgOK(DATA_MODIFY_SUCCESS);
        }

        public ActionResult ClearAllOutPutCache()
        {
            HttpRuntime.Cache.Insert(CacheDependencyKeys.Global, DateTime.Now);
            return OpContext.JsMsg("清除缓存成功！");
        }
    } 
}